var express = require("express");
var router = express.Router();
var userinfoService = require("../../service/auth/userinfoService");
var moment = require("moment");
var util = require("../../utils/util");
const authMiddleware = require("../../middleware/authMiddleware");

//注册
router.post(
    "/register",
    async (req, res, next) => {
        let { username, password, type, state, email, phone } = req.body;
        let list = await userinfoService.query({ username });
        if (list.length == 0) {
            let createtime = moment().format("YYYY-MM-DD hh:mm:ss");
            userinfoService.add({ username, password, type, state, email, phone, createtime }).then(() => {
                res.json({ code: 1, msg: "注册成功" });
            });
        } else res.json({ code: 0, msg: "用户名已存在" });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//登录
router.post(
    "/login",
    async (req, res, next) => {
        let { username, password } = req.body;
        let list = await userinfoService.query({ username, password });
        if (list.length == 0) res.json({ code: 0, msg: "账号或密码错误" });
        else if (!list[0].state) res.json({ code: 0, msg: "账号已停用" });
        else {
            let token = util.createToken({ _id: list[0]._id });
            let user = { username, email: list[0].email, role: list[0].type };
            let data = { token, user }
            res.json({ code: 1, msg: "登录成功", data });
        }
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//用户列表
router.get(
    "/list",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        let list = await userinfoService.query(req.query);
        res.json({ code: 1, data: list });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//删除
router.post(
    "/delete",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        let { _id } = req.body;
        let list = await userinfoService.delete({ _id });
        res.json({ code: 1, data: list });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//查询用户信息
router.get(
    "/model",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        let { _id } = req.query;
        let list = await userinfoService.query({ _id });
        res.json({ code: 1, data: list.length > 0 ? list[0] : {} });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//更新
router.post(
    "/update",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        let { _id, username, password, type, state, email, phone } = req.body;
        let list = await userinfoService.update({ _id, username, password, type, state, email, phone });
        res.json({ code: 1, data: list });
    },
);

module.exports = router;
